<template>
  <div class="test-container">
    <div class="top-main">
      <search :list-query="listQuery" :path="$route.name"></search>
    </div>
    <div class="bottom-main">
      <!-- <div class="list-button-group">
        <div class="button-item">
          <el-button type="primary" icon="el-icon-plus" @click="add">
            新增
          </el-button>
        </div>
      </div> -->
      <div class="table-list">
        <el-table
          ref="tableSort"
          :data="list"
          :element-loading-text="elementLoadingText"
          highlight-current-row
          height="100%"
          :header-cell-style="{
            'border-bottom': '1px solid #cbcccd',
            'border-top': '1px solid #cbcccd',
          }"
          @selection-change="setSelectRows"
        >
          <el-table-column
            show-overflow-tooltip
            type="selection"
            width="55"
            align="center"
          ></el-table-column>
          <el-table-column
            show-overflow-tooltip
            prop="renwudh"
            label="任务单号"
            align="center"
            width="200"
          ></el-table-column>
          <el-table-column
            show-overflow-tooltip
            label="起始点"
            prop="qishid"
            align="center"
            min-width="150"
          ></el-table-column>
          <!-- <el-table-column
            show-overflow-tooltip
            label="终结点"
            prop="zhongjied"
            align="center"
            min-width="150"
          ></el-table-column> -->
          <el-table-column
            show-overflow-tooltip
            label="出库单号"
            prop="chukudh"
            align="center"
            min-width="200"
          ></el-table-column>
          <el-table-column
            show-overflow-tooltip
            label="挂架码"
            prop="guajiam"
            align="center"
            width="350"
          ></el-table-column>
          <el-table-column
            show-overflow-tooltip
            label="托盘号"
            prop="tuopanh"
            align="center"
            width="150"
          ></el-table-column>
          <el-table-column
            show-overflow-tooltip
            label="货位号"
            prop="huoweih"
            align="center"
            width="150"
          ></el-table-column>
          <el-table-column
            show-overflow-tooltip
            label="备注"
            prop="tips"
            align="center"
          ></el-table-column>
          <!-- <el-table-column
            show-overflow-tooltip
            label="物资区分"
            prop="wuziqfmc"
            align="center"
          ></el-table-column>
          <el-table-column
            show-overflow-tooltip
            label="物资分类"
            prop="wuzizymc"
            align="center"
          ></el-table-column> -->
          <el-table-column
            show-overflow-tooltip
            label="状态"
            align="center"
            width="200"
          >
            <template #default="scope">
              <span v-if="scope.row.zhuangtai == 1">未开始</span>
              <span v-if="scope.row.zhuangtai == 2">进行中</span>
              <span v-if="scope.row.zhuangtai == 3">出库完成</span>
              <span v-if="scope.row.zhuangtai == 4">扫码确认</span>
            </template>
          </el-table-column>
          <el-table-column
            show-overflow-tooltip
            label="创建人"
            prop="createName"
            width="200"
            align="center"
          ></el-table-column>
          <el-table-column
            show-overflow-tooltip
            label="创建日期"
            prop="createTime"
            width="200"
            align="center"
          ></el-table-column>
          <el-table-column
            show-overflow-tooltip
            label="操作"
            fixed="right"
            min-width="200px"
          >
            <template #default="{ row }">
              <!-- <el-button type="text" @click="edit(row)">编辑</el-button> -->
              <el-button type="text" @click="showdetail(row)">明细</el-button>
              <!-- <el-button type="text" @click="delJHDByID(row)">删除</el-button> -->
              <el-button
                type="text"
                :disabled="row.zhuangtai != 1"
                @click="goDown(row)"
              >
                下发任务
              </el-button>
              <el-dropdown
                @command="updateStatuCkrwd(row, $event)"
                trigger="click"
              >
                <span class="el-dropdown-link">
                  更多
                  <i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item :command="1">未开始</el-dropdown-item>
                  <el-dropdown-item :command="2">进行中</el-dropdown-item>
                  <el-dropdown-item :command="3">出库完成</el-dropdown-item>
                  <el-dropdown-item :command="4">扫码确认</el-dropdown-item>
                  <el-dropdown-item :command="5">WCS执行完成</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        :background="background"
        :current-page="listQuery.pageIndex"
        :page-sizes="[10, 20, 30, 50]"
        :layout="layout"
        :page-size="listQuery.pageSize"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      ></el-pagination>
    </div>
    <page-2-grounding
      v-if="groundingshow"
      :gobacktitle="gobacktitle"
      :datarow="selectrow"
    ></page-2-grounding>
    <detail
      v-if="acceptshow"
      :gobacktitle="gobacktitle"
      :datarow="detailrow"
    ></detail>
    <page-2-add
      v-if="addshow"
      :gobacktitle="gobacktitle"
      :datarow="gobacktitle == '新增' ? {} : editData"
    ></page-2-add>
    <el-dialog title="托盘出口" :visible.sync="dialogFormVisible">
      <el-form
        ref="ruleForm"
        :model="form"
        label-position="left"
        :rules="rules"
      >
        <el-form-item label="出口编号" label-width="120" prop="region">
          <el-select v-model="form.region" placeholder="请选择">
            <el-option
              :disabled="lxdis"
              label="料箱拣货口:1030"
              value="1030"
            ></el-option>
            <el-option
              :disabled="lxdis"
              label="料箱出库口:1028"
              value="1028"
            ></el-option>
            <el-option
              :disabled="tpdis"
              label="托盘口:1031"
              value="1031"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('ruleForm')">
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  let _listQuery = {
    pageIndex: 1,
    pageSize: 10,
  }
  import {
    getJHDlist,
    delJHD,
    delJHDByID,
    getJHDOne,
    updateCkrwdState,
    downRWone,
    resetTask,
  } from '@/api/exwarehouse'
  import { updateLtkStatus } from '@/api/taishi'
  import search from './components/search.vue'
  import page2Grounding from './components/page2Grounding.vue'
  import Detail from './components/page2Detail.vue'
  import Page2Add from './components/page2Add.vue'
  import axios from 'axios'
  export default {
    name: 'Test',
    components: { search, page2Grounding, Detail, Page2Add },
    data() {
      return {
        listQuery: Object.assign({}, _listQuery),
        show: true,
        listLoading: true,
        total: 0,
        elementLoadingText: '正在加载...',
        list: [],
        layout: 'total,sizes,prev, pager, next, jumper',
        background: true,
        groundingshow: false,
        acceptshow: false,
        gobacktitle: '',
        selectrow: [],
        detailrow: {},
        timer: null,
        dialogFormVisible: false,
        form: {},
        rules: {
          region: [
            { required: true, message: '请选择出库口', trigger: 'change' },
          ],
        },
        sselectparams: {},
        lxdis: false,
        tpdis: false,
        addshow: false,
        editData: null,
      }
    },
    created() {
      this.fetchData()
      this.timer = setInterval(() => {
        this.fetchData()
      }, 60000)
    },
    beforeDestroy() {
      clearInterval(this.timer)
    },
    mounted() {},
    methods: {
      add() {
        this.addshow = true
        this.gobacktitle = '新增'
      },
      async edit(row) {
        const mxData = await getJHDOne({ id: row.id })
        this.addshow = true
        this.gobacktitle = '编辑'
        this.editData = mxData.data
      },
      setSelectRows(val) {
        this.selectrow = val
      },
      async fetchData() {
        let { data } = await getJHDlist(this.listQuery)
        this.total = data.total
        this.list = data.rows
      },
      handleSizeChange(val) {
        this.listQuery.pageSize = val
        this.fetchData()
      },
      updateStatuCkrwd(row, command) {
        if (row.zhuangtai == command) {
          this.$baseMessage('当前状态与操作一致，无需修改', 'error')
        } else {
          if (command == 5) {
            resetTask({ renwudh: row.renwudh }).then((res) => {
              this.$baseMessage(res.msg, 'success')
              this.fetchData()
            })
            return
          }
          updateCkrwdState({
            id: row.id,
            zhuangtai: command,
          }).then((res) => {
            this.$baseMessage(res.msg, 'success')
            this.fetchData()
          })
        }
      },
      resetStatus() {
        if (this.selectrow.zhuangtai == 4) {
          this.$confirm('将此任务重置未新单待拣货, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(async () => {
              let { data } = await updateCkrwdState({
                id: this.selectrow[0].id,
                state: '0',
              })
              this.fetchData()
            })
            .catch(() => {})
        } else {
          this.$message({
            message: '当前任务状态无法改变',
            type: 'warning',
          })
        }
      },
      handleCurrentChange(val) {
        this.listQuery.pageIndex = val
        this.fetchData()
      },
      submitForm(formName) {
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            this.sselectparams.zhongdian = this.form.region
            await axios({
              headers: {
                'Content-Type': 'application/json',
                token: localStorage.getItem('token'),
              },
              method: 'post',
              url: `http://127.0.0.1:8081/wcsgl/sendChukurwd`,
              data: JSON.stringify(this.sselectparams),
            }).then(async (res) => {
              if (res.data.code == 200) {
                // const statu = await updateCkrwdState({
                //   id: this.selectrow[0].id,
                //   state: '4',
                // })
                // this.fetchData()
                // this.$message({
                //   message: '下发任务成功',
                //   type: 'success',
                // })
                let p1 = new Promise((resolve, reject) => {
                  updateCkrwdState({
                    id: this.selectrow[0].id,
                    state: '4',
                  })
                    .then((res) => {
                      resolve(res)
                    })
                    .catch((err) => {
                      reject(err)
                    })
                })
                let p2 = new Promise((resolve, reject) => {
                  this.updateLtkStatus(this.sselectparams, '7')
                    .then((res) => {
                      resolve(res)
                    })
                    .catch((err) => {
                      reject(err)
                    })
                })
                Promise.all([p1, p2])
                  .then((res) => {
                    this.$message({
                      message: '下发任务成功',
                      type: 'success',
                    })
                    this.fetchData()
                  })
                  .catch((err) => {
                    this.$message({
                      message: '下发失败',
                      type: 'error',
                    })
                  })
              } else {
                this.$message({
                  message: res.data.message,
                  type: 'error',
                })
              }
            })
            this.dialogFormVisible = false
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      resetForm(formName) {
        this.$refs[formName].resetFields()
      },
      async fasongZJj() {
        if (this.selectrow[0].kufangmc == '托盘立体库') {
          this.lxdis = true
          this.tpdis = false
        } else {
          this.lxdis = false
          this.tpdis = true
        }
        this.dialogFormVisible = true
      },

      //更新立体库状态
      async updateLtkStatus(params, str) {
        let formdata = {
          id: params.huoweiid,
          zhuangtai: str,
        }
        let data = await updateLtkStatus(formdata)
        // if (data.code == '200') {
        //   this.$message({
        //     message: data.msg,
        //     type: 'success',
        //   })
        // }
      },
      grounding() {
        // this.groundingshow = true
        // this.gobacktitle = '生成拣货单'
        if (this.selectrow[0].zhuangtai != '0') {
          this.$message({
            message: `当前数据已经${this.$util.getJhdzt(
              this.selectrow[0].zhuangtai
            )}，请选择其他信息`,
            type: 'warning',
          })
          return
        } else {
          let data = {
            jianhuodh: this.selectrow[0].id,
            tuopanh: this.selectrow[0].tuopanh,
            huoweih: this.selectrow[0].huoweimc,
            huoweiid: this.selectrow[0].huoweiid,
            tuopanid: this.selectrow[0].tuopanid,
          }
          this.sselectparams = data
          this.fasongZJj()
        }
      },
      showdetail(row) {
        this.acceptshow = true
        this.gobacktitle = '拣货单明细'
        this.detailrow = row
      },
      searchJhd() {
        this.listQuery.pageIndex = 1
        this.fetchData()
      },
      resetlist() {
        this.listQuery = Object.assign({}, _listQuery)
        this.fetchData()
      },
      //取消任务
      async delJHD() {
        if (this.selectrow[0].zhuangtai != '0') {
          this.$message({
            message: `当前数据已经${this.$util.getJhdzt(
              this.selectrow[0].zhuangtai
            )}，请选择其他信息`,
            type: 'warning',
          })
          return
        }
        let id = this.selectrow[0].id
        let { msg } = await delJHD({ id: id })
        this.$baseMessage(msg, 'success')
        this.fetchData()
      },
      //删除交货单
      async delJHDByID(row) {
        let { msg } = await delJHDByID({ id: row.id })
        this.$baseMessage(msg, 'success')
        this.fetchData()
      },
      async goDown(row) {
        let res = await downRWone({ renwudId: row.id })
        if (res.code == 200) {
          this.$message({
            message: res.msg,
            type: 'success',
          })
          this.fetchData()
        } else {
          this.$message({
            message: res.msg,
            type: 'error',
          })
        }
      },
    },
  }
</script>
<style lang="scss" scoped>
  .test-container {
    display: flex;
    flex-direction: column;
    padding: 0 !important;
    background: #f6f8f9 !important;
    height: 100%;

    .top-main {
      width: 100%;
      background: #fff;
      padding: 10px 0;
      // .search-group {
      //   display: flex;
      //   flex-flow: row wrap;
      //   .search-gropu-item {
      //     padding: 10px 20px;
      //     width: calc((100% - 20px * 8) / 4);
      //     display: flex;
      //     label {
      //       white-space: nowrap;
      //       line-height: 32px;
      //       margin-right: 10px;
      //     }
      //     .el-select {
      //       width: 100%;
      //     }
      //   }
      //   .search-button {
      //     margin-left: auto;
      //     padding: 10px 20px;
      //     .el-button {
      //       font-size: 14px !important;
      //     }
      //   }
      // }
    }

    .bottom-main {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      flex: 1;
      background-color: #fff;
      margin-top: 10px;
      padding-bottom: 10px;

      .list-button-group {
        display: flex;
        flex-direction: row;
        padding: 20px;

        .button-item {
          padding: 0px 10px;
        }

        .button-item:first-child,
        &:last-child {
          padding: 0px 10px 0 0;
        }
      }

      .table-list {
        flex: 1;
        padding: 0 20px 20px;
      }
    }

    .el-button {
      font-size: 0.14rem !important;
    }
  }

  ::v-deep .el-dialog__body {
    padding: 20px 0 !important;
  }

  ::v-deep .el-dialog {
    width: 25% !important;
  }
  .el-dropdown-link {
    cursor: pointer;
    color: #409eff;
    margin-left: 10px;
  }

  .el-icon-arrow-down {
    font-size: 14px;
  }
</style>
